package com.newlink.building.utils.http

import com.newlink.building.utils.Module_Phone_Constants
import java.util.concurrent.TimeUnit
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody

/**
 * @Author: Jake
 * @Date: 2023/1/4
 * @Description:
 */
class Module_Phone_HttpEntity {

    private val connectionTimeout = 10
    private val readTimeout = 30

    private var url: String? = null
    private var okHttpClient: OkHttpClient? = null
    private var request: Request? = null
    private var mCallBack: Callback? = null

    init {
        okHttpClient = OkHttpClient.Builder()
            .connectTimeout(connectionTimeout.toLong(), TimeUnit.SECONDS)
            .readTimeout(readTimeout.toLong(), TimeUnit.SECONDS)
            .build()
    }

    constructor(callback: Callback?) {
        this.mCallBack = callback
        url = Module_Phone_Constants.URL
        request = Request.Builder().url(url!!).build()
    }

    constructor(url: String = Module_Phone_Constants.URL, json: String?, callback: Callback?) {

        val body: RequestBody =
            RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), json!!)
        request = Request.Builder()
            .url(url)
            .method(Module_Phone_Constants.HTTP_POST, body)
            .build()
        this.mCallBack = callback
    }

    constructor(request: Request, callback: Callback?) {
        url = request.url.toString()
        this.request = request
        this.mCallBack = callback
    }

    fun setRequestObject(url: String?, method: String?, body: RequestBody?) {
        this.url = url
        request = Request.Builder().url(url!!).method(method!!, body).build()
    }

    fun request() {
        okHttpClient!!.newCall(request!!).enqueue(mCallBack!!)
    }
}
